package com.example.springsecuritydemo2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecuritydemo2.domain.User;
import com.example.springsecuritydemo2.domain.vo.LoginUser;
import com.example.springsecuritydemo2.mapper.MenuMapper;
import com.example.springsecuritydemo2.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username.isEmpty()){
            throw new InternalAuthenticationServiceException("用户名不能为空");
        }

        // 根据用户名查询账号信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        User user = userMapper.selectOne(queryWrapper);

        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("不存在此用户");
        }

        // 2、查询权限操作
        List<String> permissions = menuMapper.selectPermsByUserId(user.getId());

        System.out.println("permissions = " + permissions);
        // 3、返回UserDetails对象
        return new LoginUser(user,permissions);

    }
}
